package com.example.demo.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Author: wenjingyuan
 * @Date: 2023/08/06/8:59
 * @Description:统一保底返回值的处理
 */
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    //将objectMapper对象注入
    @Autowired
    private ObjectMapper objectMapper;
    /**
     * 如果要实现下面这个方法就返回true
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(body instanceof ResultAjax){
            return body;
        }
        //如果body属于String类型
        if(body instanceof String){
            ResultAjax resultAjax=ResultAjax.succ(body);
            //将对象转化为json对象
            try {
             return objectMapper.writeValueAsBytes(resultAjax);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return ResultAjax.succ(body);
    }
}
